package de.tum.beilmaier.im.client.controller;

import java.util.Collection;
import java.util.Date;
import java.util.LinkedHashMap;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;

import de.novanic.eventservice.client.event.Event;
import de.novanic.eventservice.client.event.RemoteEventService;
import de.novanic.eventservice.client.event.RemoteEventServiceFactory;
import de.novanic.eventservice.client.event.domain.Domain;
import de.novanic.eventservice.client.event.listener.RemoteEventListener;
import de.tum.beilmaier.im.client.InstantChat;
import de.tum.beilmaier.im.client.MessagingService;
import de.tum.beilmaier.im.client.MessagingServiceAsync;
import de.tum.beilmaier.im.client.UserSessionHandler;
import de.tum.beilmaier.im.client.bundle.ChatRoomBundle;
import de.tum.beilmaier.im.client.event.ContactListUpdateEvent;
import de.tum.beilmaier.im.client.event.CreateChatRoomEvent;
import de.tum.beilmaier.im.client.view.ContactListWindow;
import de.tum.beilmaier.im.shared.model.ChatRoom;
import de.tum.beilmaier.im.shared.model.User;
import de.tum.beilmaier.im.shared.model.UserFlexTable;

public class ContactListController implements ClickHandler, RemoteEventListener {

	private ContactListWindow contactListWindow = null;
	private UserSessionHandler userhandler = null;
	private InstantChat imChat = null;
	private final RemoteEventServiceFactory theEventServiceFactory = RemoteEventServiceFactory.getInstance();
	private final RemoteEventService theEventService = theEventServiceFactory.getRemoteEventService();
	Domain USER_DOMAIN = null;

	public ContactListController(ContactListWindow contactListWindow, UserSessionHandler userhandler, InstantChat imChat) {
		System.out.println(this);
		this.contactListWindow = contactListWindow;
		this.userhandler = userhandler;
		this.imChat = imChat;
		USER_DOMAIN = userhandler.getLoginUser().getUserDomain();

		theEventService.addListener(USER_DOMAIN, this);
		MessagingServiceAsync messagingService = GWT.create(MessagingService.class);
		messagingService.updateContactList(USER_DOMAIN, userhandler.getLoginUser(), new AsyncCallback<Void>() {

			@Override
			public void onFailure(Throwable caught) {
				System.out.println(caught);

			}

			@Override
			public void onSuccess(Void result) {
				// TODO Auto-generated method stub

			}
		});

	}

	@Override
	public void apply(Event anEvent) {

		if (anEvent instanceof CreateChatRoomEvent)
			onMyEvent((CreateChatRoomEvent) anEvent);
		
		if (anEvent instanceof ContactListUpdateEvent)
			onMyEvent((ContactListUpdateEvent) anEvent);
	}

	private void onMyEvent(ContactListUpdateEvent event) {

		System.out.println("contactListController of User " + userhandler.getLoginUser().getName()+" forced to Refresh Contact List..");
		LinkedHashMap<String, User> contactListUsers = event.getLoginusers();
		// remove own user
		contactListUsers.remove(userhandler.getLoginUser().getUserId());

		Collection<User> userList = contactListUsers.values();
		UserFlexTable table = contactListWindow.getContactListTable();
		table.clear();

		for (User user : userList) {

			Button userBtn = new Button("CHAT");
			userBtn.addClickHandler(this);
			table.addUserToTable(user, userBtn);
		}

	}

	private void onMyEvent(CreateChatRoomEvent event) {
		System.out.println("received create chatroom.. check if available already..");
		ChatRoom chatRoom = userhandler.getLoginUser().getChatRoom(event.getChatRoom().getUUID());
		if (chatRoom != null) {
			System.out.println("chatroom found ..!");
			System.out.println("ChatRoomBundle of User according to ChatRoom Found: "+userhandler.getUserChatRoomBundles().get(event.getChatRoom().getUUID()));
//			imChat.switchViewToChatWindow(userhandler.getUserChatRoomBundles().get(event.getChatRoom().getUUID()));
		} else {
			System.out.println("no chatroom found ..! createing one..");
			chatRoom = userhandler.getLoginUser().addChatRoom(event.getChatRoom());
			
			ChatRoomBundle bundle = new ChatRoomBundle(chatRoom, userhandler, imChat);
			System.out.println("Size of PPl in Room on client side: "+ chatRoom.getChatPartners().size());
			userhandler.getUserChatRoomBundles().put(event.getChatRoom().getUUID().toString(), bundle);
			imChat.createNewChatWindow(bundle);
		}
	}

	@Override
	public void onClick(ClickEvent event) {
		int row = contactListWindow.getContactListTable().getCellForEvent(event).getRowIndex();
		User tochatwith = contactListWindow.getContactListTable().getUserAtRow(row);
		System.out.println("contactListController: User :"+userhandler.getLoginUser().getName()+" klicked Button to start chat with"+ tochatwith.getName());
		

		// trigger new create Chatroom event
		MessagingServiceAsync messagingService = GWT.create(MessagingService.class);
		messagingService.createChatRoom(USER_DOMAIN, userhandler.getLoginUser(), tochatwith, new AsyncCallback<Void>() {

			@Override
			public void onFailure(Throwable caught) {
				System.out.println(caught);

			}

			@Override
			public void onSuccess(Void result) {
				System.out.println("ContactListController: User "+userhandler.getLoginUser().getName() +" triggered Private Chat..");

			}
		});

	}

}
